package logic

import (
	"context"
	"fmt"
	"vipshops/models/cache"
	"vipshops/models/mysql"
	"vipshops/pkg"

	"vipshops/vipshoprpc/internal/svc"
	"vipshops/vipshoprpc/vipshoprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type NewPasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewNewPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *NewPasswordLogic {
	return &NewPasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *NewPasswordLogic) NewPassword(in *vipshoprpc.NewPasswordRequest) (*vipshoprpc.NewPasswordResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	mysql.DB.Debug().Where("account = ?", in.Account).Find(&user)

	if user.ID == 0 {
		return nil, fmt.Errorf("当前手机号不存在")
	}

	sms, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Account).Result()
	if sms != in.SendCode {
		return nil, fmt.Errorf("短信验证码错误")
	}

	if pkg.Md5(in.Password) == user.Password {
		return nil, fmt.Errorf("新密码和原来密码一致")
	}
	user.Password = pkg.Md5(in.Password)
	mysql.DB.Debug().Updates(&user)

	return &vipshoprpc.NewPasswordResponse{
		UserId: int64(user.ID),
	}, nil
}
